// miniprogram-frontend/pages/student/booking/booking.js
const { request } = require('../../../utils/request.js')

Page({
  data: {
    teacherId: null,
    teacherInfo: {},
    headerHeight: 0,
    
    // 日历相关
    year: 0,
    month: 0,
    days: [],
    selectedDate: '',
    
    // 教师课程安排数据（用于判断哪些日期有课，哪些时间段有课）
    teacherSchedule: {},
    
    // 固定的三个时间段
    fixedTimeSlots: [
      {
        id: 'morning',
        name: '早上',
        startTime: '08:30',
        endTime: '12:00',
        duration: 210 // 分钟
      },
      {
        id: 'afternoon', 
        name: '下午',
        startTime: '13:30',
        endTime: '18:00',
        duration: 270 // 分钟
      },
      {
        id: 'evening',
        name: '晚上', 
        startTime: '19:00',
        endTime: '22:00',
        duration: 180 // 分钟
      }
    ],
    
    // 当前可用的时间段
    availableTimeSlots: [],
    loading: false,
    
    // 预约弹窗
    showBookingModal: false,
    selectedTimeSlot: null,
    
    // 时间选择器相关
    showTimePicker: false,
    selectedHour: '',
    selectedMinute: '',
    hourOptions: ['08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21'],
    minuteOptions: ['00', '15', '30', '45'],
    selectedTime: '',
    
    // 时长选择相关
    selectedDuration: 'trial',
    durationOptions: [
      { id: 'trial', name: '40分钟', type: 'trial', price: 9.9 },
      { id: 'formal', name: '2小时', type: 'formal', price: 0 }
    ],
    
    // 试听价格
    trialPrice: 9.9
  },

  onLoad(options) {
    const teacherId = options.teacherId
    if (!teacherId) {
      wx.showToast({
        title: '缺少教师信息',
        icon: 'none'
      })
      setTimeout(() => wx.navigateBack(), 1500)
      return
    }

    this.setData({ teacherId })
    
    // 初始化日历
    const now = new Date()
    this.setData({ 
      year: now.getFullYear(), 
      month: now.getMonth() + 1 
    })
    this.buildMonth(now.getFullYear(), now.getMonth() + 1)
    this.setSelected(this.dateToStr(now))
    
    // 加载教师信息和课程安排
    this.loadTeacherInfo()
    this.loadTeacherSchedule()
  },

  // onHeaderReady(e) {
  //   this.setData({ headerHeight: e.detail.totalHeight || 0 })
  // },

  // 加载教师信息
  async loadTeacherInfo() {
    try {
      console.log('Loading teacher info for:', this.data.teacherId)
      
      // 这里可以调用获取教师详情的接口
      // 暂时使用占位数据
      const teacherInfo = {
        id: this.data.teacherId,
        name: '教师姓名',
        avatar: '/images/default-avatar.png',
        subjects: 'AP经济 | NEC经济竞赛'
      }
      
      this.setData({ teacherInfo })
    } catch (error) {
      console.error('Load teacher info error:', error)
    }
  },

  // 加载教师课程安排数据
  async loadTeacherSchedule() {
    try {
      console.log('Loading teacher schedule for teacher:', this.data.teacherId)
      
      // 这里应该调用后端接口获取教师的课程安排
      // 暂时使用模拟数据
      const teacherSchedule = {
        // 格式：日期 -> 时间段数组
        '2025-07-01': ['morning', 'afternoon'], // 有早上和下午的课
        '2025-07-03': ['evening'], // 有晚上的课
        '2025-07-05': ['morning'], // 有早上的课
        '2025-07-10': ['afternoon', 'evening'], // 有下午和晚上的课
        // 可以继续添加更多日期...
      }
      
      this.setData({ teacherSchedule })
      
      // 重新构建日历以显示有课日期的标记
      this.buildMonth(this.data.year, this.data.month)
      
      // 更新当前选中日期的可用时间段
      this.updateAvailableTimeSlots()
      
    } catch (error) {
      console.error('Load teacher schedule error:', error)
      wx.showToast({
        title: '加载课程安排失败',
        icon: 'none'
      })
    }
  },

  // 日历相关方法
  dateToStr(d) {
    const y = d.getFullYear()
    const m = ('0' + (d.getMonth() + 1)).slice(-2)
    const da = ('0' + d.getDate()).slice(-2)
    return `${y}-${m}-${da}`
  },

  buildMonth(year, month) {
    const first = new Date(year, month - 1, 1)
    const daysInMonth = new Date(year, month, 0).getDate()
    const res = []
    
    for (let i = 1; i <= daysInMonth; i++) {
      const currentDate = new Date(year, month - 1, i)
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      currentDate.setHours(0, 0, 0, 0)
      
      // 构建日期字符串
      const dateStr = `${year}-${('0' + month).slice(-2)}-${('0' + i).slice(-2)}`
      
      // 检查该日期是否有课程安排
      const hasClass = this.data.teacherSchedule[dateStr] && this.data.teacherSchedule[dateStr].length > 0
      
      res.push({ 
        date: i, 
        isCurrent: true, 
        selected: false, 
        isToday: currentDate.getTime() === today.getTime(),
        isPast: currentDate.getTime() < today.getTime(),
        hasClass: hasClass // 是否有课程安排
      })
    }
    
    this.setData({ days: res })
  },

  setSelected(dateStr) {
    const d = new Date(dateStr.replace(/-/g, '/'))
    const sel = d.getDate()
    const days = this.data.days.map((x, idx) => ({ 
      ...x, 
      selected: (idx + 1) === sel 
    }))
    this.setData({ days, selectedDate: dateStr })
    
    // 更新该日期的可用时间段
    this.updateAvailableTimeSlots()
  },

  // 更新当前选中日期的可用时间段
  updateAvailableTimeSlots() {
    const { selectedDate, teacherSchedule, fixedTimeSlots } = this.data
    
    if (!selectedDate) {
      this.setData({ availableTimeSlots: [] })
      return
    }
    
    // 获取该日期教师的课程安排
    const busySlots = teacherSchedule[selectedDate] || []
    
    // 过滤出可用的时间段（没有被占用的时间段）
    const availableTimeSlots = fixedTimeSlots.filter(slot => {
      return !busySlots.includes(slot.id)
    }).map(slot => ({
      ...slot,
      status: 'available',
      type: 'trial'
    }))
    
    console.log('Selected date:', selectedDate)
    console.log('Busy slots:', busySlots)
    console.log('Available slots:', availableTimeSlots)
    
    this.setData({ availableTimeSlots })
  },

  prevMonth() {
    let { year, month } = this.data
    month--
    if (month === 0) {
      month = 12
      year--
    }
    this.setData({ year, month })
    this.buildMonth(year, month)
  },

  nextMonth() {
    let { year, month } = this.data
    month++
    if (month === 13) {
      month = 1
      year++
    }
    this.setData({ year, month })
    this.buildMonth(year, month)
  },

  onSelectDay(e) {
    const idx = e.currentTarget.dataset.index
    const day = idx + 1
    const y = this.data.year
    const m = ('0' + this.data.month).slice(-2)
    const d = ('0' + day).slice(-2)
    const ds = `${y}-${m}-${d}`
    
    // 检查是否是过去的日期
    const selectedDate = new Date(y, this.data.month - 1, day)
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    selectedDate.setHours(0, 0, 0, 0)
    
    if (selectedDate.getTime() < today.getTime()) {
      wx.showToast({
        title: '不能选择过去的日期',
        icon: 'none'
      })
      return
    }
    
    this.setSelected(ds)
  },

  // 预约试听
  onBookTrial(e) {
    const slotId = e.currentTarget.dataset.slotid
    const timeSlot = this.data.availableTimeSlots.find(slot => slot.id === slotId)
    
    if (!timeSlot) return
    
    if (timeSlot.status !== 'available') {
      wx.showToast({
        title: '该时间段不可预约',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      selectedTimeSlot: timeSlot,
      showBookingModal: true
    })
  },

  // 隐藏预约弹窗
  hideBookingModal() {
    this.setData({
      showBookingModal: false,
      selectedTimeSlot: null,
      showTimePicker: false,
      selectedHour: '',
      selectedMinute: '',
      selectedTime: '',
      selectedDuration: 'trial'
    })
  },

  // 切换时间选择器显示
  toggleTimePicker() {
    this.setData({
      showTimePicker: !this.data.showTimePicker
    })
  },

  // 选择小时
  onHourChange(e) {
    const hour = this.data.hourOptions[e.detail.value]
    this.setData({ selectedHour: hour })
    this.updateSelectedTime()
  },

  // 选择分钟
  onMinuteChange(e) {
    const minute = this.data.minuteOptions[e.detail.value]
    this.setData({ selectedMinute: minute })
    this.updateSelectedTime()
  },

  // 更新选中的时间显示
  updateSelectedTime() {
    const { selectedHour, selectedMinute } = this.data
    if (selectedHour && selectedMinute) {
      this.setData({
        selectedTime: `${selectedHour}:${selectedMinute}`,
        showTimePicker: false
      })
    }
  },

  // 选择时长
  onDurationSelect(e) {
    const durationId = e.currentTarget.dataset.id
    this.setData({ selectedDuration: durationId })
  },

  // 确认预约
  async confirmBooking() {
    const { selectedTime, selectedDuration, teacherId, selectedDate, selectedTimeSlot } = this.data
    
    // 验证必填项
    if (!selectedTime) {
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none'
      })
      return
    }
    
    try {
      wx.showLoading({ title: '预约中...' })
      
      const api = require('../../../utils/api')
      
      // 构建预约数据，保存到student_survey表
      const surveyData = {
        teacherId: parseInt(teacherId),
        data: {
          bookingType: 'trial',
          selectedDate: selectedDate,
          selectedTime: selectedTime,
          timeSlotName: selectedTimeSlot.name,
          duration: selectedDuration,
          trialPrice: this.data.trialPrice,
          bookingTime: new Date().toISOString()
        },
        status: 0, // 待处理
        courseTitle: `试听课预约 - ${selectedDate} ${selectedTime}`
      }
      
      console.log('Booking survey data:', surveyData)
      
      // 调用survey保存接口
      const response = await api.survey.save(surveyData)
      
      if (response && response.success) {
        wx.hideLoading()
        this.hideBookingModal()
        
        wx.showModal({
          title: '预约成功',
          content: '试听课程预约成功，请等待教师确认',
          showCancel: false,
          confirmText: '确定',
          success: () => {
            // 刷新时间段
            this.updateAvailableTimeSlots()
          }
        })
      } else {
        throw new Error(response.message || '预约失败')
      }
      
    } catch (error) {
      wx.hideLoading()
      console.error('Booking error:', error)
      wx.showToast({
        title: error.message || '预约失败，请重试',
        icon: 'none'
      })
    }
  },

  // 格式化时间长度
  formatDuration(minutes) {
    if (minutes < 60) {
      return `${minutes}分钟`
    } else {
      const hours = Math.floor(minutes / 60)
      const remainMinutes = minutes % 60
      return remainMinutes > 0 ? `${hours}小时${remainMinutes}分钟` : `${hours}小时`
    }
  }
})
